﻿using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Windows;
using Caliburn.Micro;
using RatingAuthor;
using SamizdatSearch;
using System;

namespace ConditionTreeTestStand
{
  public class SelectGenresViewModel : Screen
  {
    private readonly GenresLookup _genresLookup;
    private readonly Action<GenresSet> _done;

    public SelectGenresViewModel(GenresLookup genresLookup, GenresSet current, Action<GenresSet> done)
    {
      _genresLookup = genresLookup;
      _done = done;
      GenresSelection = 
        genresLookup.Values.Select(g => 
          new GenreSelecor(g, () => _done(Result), current[genresLookup[g]])).ToList();
    }
    public override void AttachView(object view, object context)
    {
      base.AttachView(view, context);
      var win = view as Window;
      if (win != null)
      {
        EventHandler handler = (s, e) => win.Close();
        win.Deactivated += handler;
        win.Closing += (s, e) =>
                         {
                           _done(Result);
                           win.Deactivated -= handler;
                         };
      }
    }
    public IEnumerable<GenreSelecor> GenresSelection { get; private set; }
    public GenresSet Result
    {
      get
      {
        return _genresLookup.Lookup(
          from s in GenresSelection 
          where s.IsSelected 
          select s.Name);
      }
    }
  }
}